package kr.ac.skhu.m.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.transaction.UnexpectedRollbackException;

import kr.ac.skhu.m.util.EncodingUtil;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

/**
 * Servlet implementation class RentalYn
 */
@WebServlet("/RentalYn")
public class RentalYn extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RentalYn() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		
		String book_id = request.getParameter("book_id");
		PrintWriter out = response.getWriter();
		
		//대여여부
		String detailUrl = "http://library.skhu.ac.kr/DLiWeb20/components/searchir/detail/detail.aspx?cid=" + book_id;
		Source detailSource = new Source(new URL(detailUrl));
		detailSource.fullSequentialParse();
		
		List<Element> td_white_left = detailSource.getAllElementsByClass("td_white_left");
		int td_white_left_length = td_white_left.size();
		
		String rentalYn = "";
		int bookCount = 0;
		
		try{
			for(int i=0; i<td_white_left_length; i++){
				if( i%3 == 1 ){
					rentalYn += (++bookCount) + ". " + td_white_left.get(i).getTextExtractor().toString() + "$";
				}
			}
			
		}catch(Exception e){
			rentalYn = "";
		}

		out.print(rentalYn);
	}

}
